package com.mf.morefun.util;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.apkfuns.logutils.Constant;
import com.mf.morefun.bean.LocalListenBean;


import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.ParserConfigurationException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtils {
    private static final String DOWNLOAD_URL = "/download?_o=%2Fsearch%2Fsong";
    private static final int SUCCESS_LRC = 1;//下载歌词成功
    private static final int FAILED_LRC = 2;//下载歌词失败
    private static final int SUCCESS_MP3 = 3;//下载歌曲成功
    private static final int FAILED_MP3 = 4;//下载歌曲失败
    private static final int GET_MP3_URL = 5;//获取音乐下载地址成功
    private static final int GET_FAILED_MP3_URL = 6;//获取音乐下载地址失败
    private static final int MUSIC_EXISTS = 7;//下载时,音乐已存在

    private static DownloadUtils sInstance;
    private OnDownloadListener mListener;

    private ExecutorService mThreadPool;

    /**
     *设置回调监听器对象
     * @param mListener
     * @return
     */
    public DownloadUtils setListener(OnDownloadListener mListener){
        this.mListener = mListener;
        return this;
    }

    //获取下载工具的实例
    public synchronized static DownloadUtils getsInstance(){
        if (sInstance == null){
            try {
                sInstance = new DownloadUtils();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
        }
        return  sInstance;
    }

    /**
     * 下载的具体业务方法
     * @throws ParserConfigurationException
     */
    private DownloadUtils() throws ParserConfigurationException{
        mThreadPool = Executors.newSingleThreadExecutor();
    }

    public void download(final LocalListenBean searchResult){
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case SUCCESS_LRC:
                        if (mListener != null) mListener.onDowload("歌词下载成功");
                        break;
                    case FAILED_LRC:
                        if (mListener != null) mListener.onFailed("歌词下载失败");
                        break;
                    case GET_MP3_URL:
                        System.out.println("GET_MP3_URL:"+msg.obj);
                        downloadMusic(searchResult,(String)msg.obj,this);
                        break;
                    case GET_FAILED_MP3_URL:
                        if (mListener != null) mListener.onFailed("下载失败,该歌曲为收费或VIP类型");
                        break;
                    case SUCCESS_MP3:
                        if (mListener != null) mListener.onDowload(searchResult.getLocalListenUrl());
                        break;
                    case FAILED_MP3:
                        if (mListener != null) mListener.onFailed(searchResult.getMusicName()+"下载失败");
                        break;
                    case MUSIC_EXISTS:
                        if (mListener != null) mListener.onDowload(searchResult.getLocalListenUrl());

                        break;
                }
            }
        };
        Message msg = handler.obtainMessage(GET_MP3_URL,searchResult.getNetListenUrl());
        msg.sendToTarget();
    }

    //下载MP3
    private void downloadMusic(final LocalListenBean searchResult,final String url,final Handler handler){
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                File musicDirFile = new File(Environment.getExternalStorageDirectory() + "/listenMusic");
                if (!musicDirFile.exists()){
                    musicDirFile.mkdirs();
                }

                String mp3url = url;

                String target = musicDirFile + "/" + searchResult.getMusicName() + ".mp3";
                System.out.println(mp3url);
                System.out.println(target);
                File fileTarget = new File(target);
                if (fileTarget.exists()){
                    searchResult.setLocalListenUrl(target);
                    handler.obtainMessage(MUSIC_EXISTS).sendToTarget();
                    return;
                }else {
                    //使用OkHttpClient组件
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(mp3url).build();
                    System.out.println(request);
                    try {
                        Response response = client.newCall(request).execute();
                        if (response.isSuccessful()){
                            PrintStream ps = new PrintStream(fileTarget);
                            byte[] bytes = response.body().bytes();
                            ps.write(bytes,0,bytes.length);
                            ps.close();
                            searchResult.setLocalListenUrl(target);
                            handler.obtainMessage(SUCCESS_MP3).sendToTarget();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.obtainMessage(FAILED_MP3).sendToTarget();
                    }
                }
            }
        });
    }

    //自定义下载事件监听器
    public interface OnDownloadListener {
        public void onDowload(String mp3Url);
        public void onFailed(String error);
    }
}
